package com.example.bawolf.thread;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.CyclicBarrier;
import java.util.stream.IntStream;

/**
 * @author zhougf
 * @version 1.0
 * @date 2020/06/09
 */
public class CyclicBarrierTest {
    public static void main(String[] args) throws InterruptedException {
        System.out.println(new Date() + "\t" + Thread.currentThread().getName() + "\t\trunning...");
        Random random = new Random();
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
        Runnable runnable = () -> {
            System.out.println(new Date() + "\t" + Thread.currentThread().getName() + "\trunning...");
            try {
                int i = random.nextInt(10);
                if( i / 2 == 0) {
                    System.out.println(new Date() + "\t" + Thread.currentThread().getName() +"\t" +i +"\t等待...");

                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
            }

            try { cyclicBarrier.await(); } catch (Exception e) { }
            System.out.println(new Date() + "\t" + Thread.currentThread().getName() + "\tover");
        };


        IntStream.range(0, 7).forEach(j -> {
            new Thread(runnable).start();
        });
    }

}
